package com.toKnow.controller;

import com.toKnow.model.entity.Article;
import com.toKnow.model.entity.Source;
import com.toKnow.model.vo.ArticleVo;
import com.toKnow.model.vo.BasicVo;
import com.toKnow.model.vo.SourceVo;
import com.toKnow.service.ArticleService;
import com.toKnow.service.CreatorService;
import com.toKnow.service.SourceService;
import com.toKnow.utils.JwtUserSessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/api/creator")
public class CreatorApiController {
  @Autowired
  CreatorService creatorService;
  @Autowired
  ArticleService articleService;
  @Autowired
  SourceService sourceService;

  public Integer getUid(HttpSession session){
    try{
      String token = (String) session.getAttribute("userToken");
      return Integer.parseInt(JwtUserSessionUtil.getInfo(token,"id"));
    } catch (Exception e){
      return null;
    }
  }

  @ResponseBody
  @RequestMapping(value = "article/draft", method = RequestMethod.POST)
  public BasicVo getArticleDraft(HttpSession session, Integer id) {
    Integer uid = getUid(session);
    if(uid == null) {
      return new BasicVo(false, "请先登录", null);
    }

    Article draft = articleService.selectArticleDraftById(uid, id);
    if(draft == null) return new BasicVo(false, "没有找到草稿", null);
    ArticleVo vo = new ArticleVo(draft);

    return new BasicVo(true, "", vo);
  }

  @ResponseBody
  @RequestMapping(value = "source/draft", method = RequestMethod.POST)
  public BasicVo getSourceDraft(HttpSession session, Integer id) {
    Integer uid = getUid(session);
    if(uid == null) {
      return new BasicVo(false, "请先登录", null);
    }

    Source draft = sourceService.selectSourceDraftById(uid, id);
    if(draft == null) return new BasicVo(false, "没有找到草稿", null);
    System.out.println(draft);
    SourceVo vo = new SourceVo(draft);
    System.out.println(vo);

    return new BasicVo(true, "", vo);
  }
}
